import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../models/post.dart';
import '../screens/post_detail_page.dart';
import '../routes/routes.dart';
import 'video_player_widget.dart';

class PostListItem extends StatefulWidget {
  final Post post;

  const PostListItem({Key? key, required this.post}) : super(key: key);

  @override
  _PostListItemState createState() => _PostListItemState();
}

class _PostListItemState extends State<PostListItem> {
  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
      elevation: 0.5,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12.0),
      ),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 用户信息行
            Row(
              children: [
                // 用户头像 - 添加点击事件跳转到用户详情页
                GestureDetector(
                  onTap: () {
                    Get.toNamed(
                      AppRoutes.userProfile, 
                      arguments: {
                        'userId': widget.post.userId,
                        'userNickname': widget.post.userNickname,
                        'userAvatarUrl': widget.post.userAvatarUrl,
                      }
                    );
                  },
                  child: CircleAvatar(
                    radius: 20,
                    backgroundImage: NetworkImage(widget.post.userAvatarUrl),
                  ),
                ),
                const SizedBox(width: 12),
                
                // 用户名和发布时间
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        widget.post.userNickname,
                        style: const TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                        ),
                      ),
                      Text(
                        _getTimeAgo(widget.post.ctime),
                        style: TextStyle(
                          color: Colors.grey[600],
                          fontSize: 12,
                        ),
                      ),
                    ],
                  ),
                ),
                
                // 关注按钮 - 单独的点击事件
                OutlinedButton(
                  onPressed: () {
                    // 关注/取消关注逻辑
                    setState(() {
                      widget.post.isFollowed = !widget.post.isFollowed;
                    });
                    // 显示提示
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: Text(widget.post.isFollowed ? '已关注该用户' : '已取消关注'),
                        duration: const Duration(seconds: 1),
                      ),
                    );
                  },
                  style: OutlinedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 0),
                    minimumSize: Size.zero,
                    tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(16),
                    ),
                  ),
                  child: Text(
                    widget.post.isFollowed ? '已关注' : '关注',
                    style: TextStyle(
                      fontSize: 12,
                      color: widget.post.isFollowed ? Colors.grey : Colors.blue,
                    ),
                  ),
                ),
              ],
            ),
            
            const SizedBox(height: 12),
            
            // 帖子内容区域 - 可点击跳转到详情页
            GestureDetector(
              onTap: () {
                // 跳转到帖子详情页
                Get.toNamed(AppRoutes.postDetail, arguments: {'post': widget.post});
              },
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 帖子标题
                  if (widget.post.title.isNotEmpty)
                    Padding(
                      padding: const EdgeInsets.only(bottom: 8.0),
                      child: Text(
                        widget.post.title,
                        style: const TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                        ),
                      ),
                    ),
                  
                  // 帖子内容
                  Text(
                    widget.post.content,
                    maxLines: 3,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(fontSize: 14),
                  ),
                  
                  const SizedBox(height: 12),
                  
                  // 图片区域
                  if (widget.post.images.isNotEmpty)
                    _buildImagePreview(widget.post.images),
                    
                  // 视频预览
                  if (widget.post.videoUrl != null)
                    VideoPlayerWidget(videoUrl: widget.post.videoUrl!),
                ],
              ),
            ),
                
            const SizedBox(height: 12),
            
            // 互动按钮行 - 每个按钮有独立的点击事件
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                // 点赞按钮
                InkWell(
                  onTap: () {
                    setState(() {
                      widget.post.isLiked = !widget.post.isLiked;
                      widget.post.likesCount += widget.post.isLiked ? 1 : -1;
                    });
                  },
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Row(
                      children: [
                        Icon(
                          widget.post.isLiked ? Icons.favorite : Icons.favorite_border,
                          size: 18,
                          color: widget.post.isLiked ? Colors.red : Colors.grey,
                        ),
                        const SizedBox(width: 4),
                        Text(
                          '${widget.post.likesCount}',
                          style: TextStyle(
                            color: widget.post.isLiked ? Colors.red : Colors.grey,
                            fontSize: 14,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                
                // 评论按钮 - 跳转到详情页并聚焦评论区
                InkWell(
                  onTap: () {
                    Get.toNamed(AppRoutes.postDetail, arguments: {'post': widget.post, 'focusComment': true});
                  },
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Row(
                      children: [
                        const Icon(
                          Icons.comment_outlined,
                          size: 18,
                          color: Colors.grey,
                        ),
                        const SizedBox(width: 4),
                        Text(
                          '${widget.post.commentsCount}',
                          style: const TextStyle(
                            color: Colors.grey,
                            fontSize: 14,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                
                // 分享按钮
                InkWell(
                  onTap: () {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text('分享功能待实现'),
                        duration: Duration(seconds: 1),
                      ),
                    );
                  },
                  child: const Padding(
                    padding: EdgeInsets.all(8.0),
                    child: Row(
                      children: [
                        Icon(
                          Icons.share_outlined,
                          size: 18,
                          color: Colors.grey,
                        ),
                        SizedBox(width: 4),
                        Text(
                          '分享',
                          style: TextStyle(
                            color: Colors.grey,
                            fontSize: 14,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 构建图片预览
  Widget _buildImagePreview(List<String> images) {
    if (images.length == 1) {
      // 单张图片
      return ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: Image.network(
          images[0],
          height: 200,
          width: double.infinity,
          fit: BoxFit.cover,
        ),
      );
    } else {
      // 多张图片网格
      return GridView.count(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        crossAxisCount: 3,
        mainAxisSpacing: 4,
        crossAxisSpacing: 4,
        children: images.take(9).map((url) {
          return ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Image.network(
              url,
              fit: BoxFit.cover,
            ),
          );
        }).toList(),
      );
    }
  }

  // 构建视频预览
  Widget _buildVideoPreview() {
    return Container(
      height: 200,
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Stack(
        alignment: Alignment.center,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: Image.network(
              'https://via.placeholder.com/400x200/000000/FFFFFF?text=Video+Thumbnail',
              fit: BoxFit.cover,
              width: double.infinity,
            ),
          ),
          Icon(
            Icons.play_circle_fill,
            size: 50,
            color: Colors.white.withOpacity(0.8),
          ),
        ],
      ),
    );
  }

  // 获取时间显示
  String _getTimeAgo(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);
    
    if (difference.inDays > 365) {
      return '${(difference.inDays / 365).floor()}年前';
    } else if (difference.inDays > 30) {
      return '${(difference.inDays / 30).floor()}月前';
    } else if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }
}